package com.bolehui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bolehui.base.result.Result;
import com.bolehui.base.utils.DateUtil;
import com.bolehui.base.utils.LogUtil;
import com.bolehui.domain.po.Message;
import com.bolehui.mapper.MessageMapper;
import com.bolehui.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName MessageServiceImpl
 * @Description
 * @createTime 2025/3/15-13:25
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Override
    public Message saveMessage(Message message) {
        // 设置消息的发送时间
        message.setIsRead(0);
        // 调用 MyBatis-Plus 的 insert 方法，将消息存储到数据库
        messageMapper.insert(message);

        // 返回保存后的消息对象
        return message;
    }

    @Override
    public Result findMessageByConversationId(Long id) {
        List<Message> messages = messageMapper.selectList(new QueryWrapper<Message>().eq("conversation_id", id).orderByAsc("create_time"));// 按时间排序);
        return Result.success(messages);
    }

    @Override
    public Result updateUnreadById(Long conversationId, Long senderId) {
        if (conversationId == null || senderId == null) {
            return Result.fail("Invalid conversationId or senderId");
        }

        try {
            Message message = new Message();
            message.setIsRead(1);

            QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("conversation_id", conversationId)
                    .eq("sender_id", senderId);

            messageMapper.update(message, queryWrapper);
            return Result.success();
        } catch (Exception e) {
            return Result.fail("Update failed due to an internal error");
        }
    }


}
